package com.example.housingRentalSystem.controller;

import com.example.housingRentalSystem.bean.News;
import com.example.housingRentalSystem.service.NewsService;
import com.example.housingRentalSystem.utils.ApiResponse;
import com.example.housingRentalSystem.utils.HttpStatus;
import com.example.housingRentalSystem.utils.PageRequest;
import com.example.housingRentalSystem.utils.PageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Optional;

/**
 * @author 王硕
 * @version jdk21
 * @className NewsController
 * @description 新闻控制器
 * @date 2025/3/24 16:22
 */
@RestController
@RequestMapping("/api/news")
public class NewsController {

    @Autowired
    private NewsService newsService;

    @GetMapping("/list")
    public ApiResponse<PageResponse<News>> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size
    ) {
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPage(page);
        pageRequest.setSize(size);
        return ApiResponse.success(newsService.getList(pageRequest));
    }

    @GetMapping("/detail/{id}")
    public ResponseEntity<ApiResponse<News>> detail(@PathVariable Integer id) {
        Optional<News> optionalNews = newsService.getDetail(id);
        if (optionalNews.isPresent()) {
            return ResponseEntity.ok(ApiResponse.success(optionalNews.get()));
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @PostMapping("/add")
    public ApiResponse<Void> add(@Valid @RequestBody News news) {
        newsService.addNews(news);
        return ApiResponse.success(HttpStatus.OK.getCode(), "添加成功");
    }

    @PutMapping("/update/{id}")
    public ApiResponse<Void> update(@PathVariable Integer id, @Valid @RequestBody News news) {
        newsService.updateNews(id, news);
        return ApiResponse.success(HttpStatus.OK.getCode(), "更新成功");
    }

    @DeleteMapping("/delete/{id}")
    public ApiResponse<Void> delete(@PathVariable Integer id) {
        newsService.deleteNews(id);
        return ApiResponse.success(HttpStatus.OK.getCode(), "删除成功");
    }
    @GetMapping("/selectCountNews")
    public ApiResponse<Integer> selectCountNews() {
        return ApiResponse.success(newsService.selectCountNews());
    }
}